/**
 * Script of the video list for a tag page
 */
var PageTagVideoList = new (function() {
	var $this = this;
	var videosDisplayed = [];
	var loadingFirst = false;
	var loadingNext = false;
	var haveMore = true;
	var haveError = false;
	var ajax;
	
	/**
	 * Initialization
	 * Load the last status saved
	 */
	this.init = function(e, data) {

		loadVideoTag();
		if (!videosDisplayed.length && !$("#tag-offset").val()) {
			$this.searchVideos();
		}
	}
	
	/**
	 * Empty the search and the page
	 */
	this.reset = function() {
		videosDisplayed = [];
		haveError = false;
		window.localStorage.removeItem('page_tagVideoList');
		if (ajax) {
			ajax.abort();
			ajax = null;
		}
	}
	
	/**
	 * Search a video with a tag
	 */
	this.searchVideos = function() {
		var tag = $("#tag").val();
		var dataAjax = {
			tag: tag,
			login: MikuClip.options.login, 
			password: MikuClip.options.password,
			sort: $("#tag-sort").val()
		};
		
		if ($("#tag-offset").val()) {
			dataAjax.offset = $("#tag-offset").val();
		}
		
		if (ajax) {
			ajax.abort();
			ajax = null;
		}
		
		haveMore = true;
		loadingFirst = false;
		loadingNext = false;
		haveError = false;
		
		if (!dataAjax.offset) {
			loadingFirst = true;
			clearListView();
			videosDisplayed = [];
		}
		else {
			loadingNext = true;
		}
		updateListView();
		
		ajax = $.ajax({
			url: MikuClip.URL.WEBSERVICE_VIDEOS_TAGS,
			data: dataAjax,
			type: 'POST',
			success: function(data) {
				try {
					var videos = JSON.parse(data);
					saveVideoTag();
					if (videos.error_type && videos.error_type == "connection") {
						DialogConnectMikubook.setError(videos.error);
						DialogConnectMikubook.show();
					}
					else {
						for (var i = 0; i < videos.length; i++) {
							addToListView(videos[i]);
							videosDisplayed.push(videos[i]);
						}
						
						if (videos.length == 0) {
							haveMore = false;
						}
						
						loadingNext = false;
						loadingFirst = false;
						
						updateListView();
						$("#tag-offset").val($("#page-tag-videolist #listview .video-item").length);
						
						saveVideoTag();
						ajax = null;
					}
				}
				catch (e) {
					onError({statusText: 'parsing_error'});
				}
			},
			error: onError
		});
	}
	
	/**
	 * Error occured (403, 404, ...) or parsing error
	 */	
	function onError(e) {
		loadingNext = false;
		loadingFirst = false;
		if (e.statusText != "abort") {
			haveError = true;
		}
		ajax = null;
		updateListView();
	}
	
	/**
	 * Click on the refresh button
	 */ 
	function onRefresh() {
		videosDisplayed = [];
		$("#tag-offset").val('');
		$("#page-tag-videolist #listview .video-item").remove();
		$this.searchVideos();
	}
	
	
	/**
	 * Click on a tab for sorting resukts
	 */
	function onSort() {
		var link = $(this);
		clearListView();
		videosDisplayed = [];
		haveError = false;
		
		updateListView();
		saveVideoTag();
		
		if (ajax) {
			ajax.abort();
			ajax = null;
		}
		
		$("#tag-offset").val('');
		$("#tag-sort").val(link.attr("sort-data"));

		$this.searchVideos();	
	}
	
	/**
	 * Save the current status of the page (video loading, videos displayed, offset)
	 */
	function saveVideoTag() {
		window.localStorage['page_tagVideoList'] = JSON.stringify({
			'tag': $("#tag").val(),
			'offset': $("#tag-offset").val(),
			'videos': videosDisplayed,
			'loadingFirst': loadingFirst,
			'loadingNext': loadingNext,
			'haveMore': haveMore,
			'sort': $("#tag-sort").val()
		});
	}
	

	/**
	 * Load the saved status of the page
	 */
	function loadVideoTag() {
		if (window.localStorage['page_tagVideoList']) {
			var o = JSON.parse(window.localStorage['page_tagVideoList']);
			
			$("#tag").val(o.tag);
			$("#span-tag").html(o.tag);
			$("#tag-offset").val(o.offset);
			$("#tag-sort").val(o.sort);
			
			$("#page-tag-videolist .btn-listview-sort").removeClass("ui-btn-active");
			$("#page-tag-videolist .btn-listview-sort[sort-data='"+o.sort+"']").addClass("ui-btn-active");
			
			loadingFirst = o.loadingFirst;
			loadingNext = o.loadingNext;
			haveMore = o.haveMore;
			
			videosDisplayed = [];
			clearListView();
			if (!o.loadingFirst) {
				for (var i = 0; i < o.videos.length; i++) {
					addToListView(o.videos[i]);
					videosDisplayed.push(o.videos[i]);
				}
			}
			
			updateListView();
			
			if (o.loadingNext || o.loadingFirst) {
				$this.searchVideos();
			}
			
		}
	}
	
	/**
	 * Update the main listview (more element, loading, error, no videos)
	 */
	function updateListView() {
		if (loadingFirst) {
			$("#page-tag-videolist #listview-loader-top").css("display", "block");
		}
		else {
			$("#page-tag-videolist #listview-loader-top").css("display", "none");
		}
		
		if (loadingNext) {
			$("#page-tag-videolist #listview-loader-bottom").css("display", "block");
		}
		else {
			$("#page-tag-videolist #listview-loader-bottom").css("display", "none");
		}
		
		if (videosDisplayed.length && haveMore && !loadingFirst && !loadingNext) {
			$("#page-tag-videolist #listview-item-more").css("display", "block");
		}
		else {
			$("#page-tag-videolist #listview-item-more").css("display", "none");
		}
	
	
		if (!haveError && !videosDisplayed.length && !loadingFirst && !loadingNext) {
			$("#page-tag-videolist #listview-item-notfound").css("display", "block");
		}
		else {
			$("#page-tag-videolist #listview-item-notfound").css("display", "none");
		}

		if (haveError) {
			$("#page-tag-videolist #listview-item-error").css("display", "block");
		}
		else {
			$("#page-tag-videolist #listview-item-error").css("display", "none");
		}
		
		refreshListView();
	}
	
	/**
	 * Clear the main list view
	 */
	function clearListView() {
		$("#page-tag-videolist #listview .video-item").remove();
		refreshListView();
	}
	
	/**
	 * Add an video to listview
	 */
	function addToListView(videodata) {
		var video = new VideoItem(videodata);
		$("#page-tag-videolist #listview-loader-bottom").before(video.dom);
		refreshListView();
	}
	
	/**
	 * Refresh the JQuery Mobile Widget, if loaded
	 */
	function refreshListView() {
		try {
			$("#page-tag-videolist #listview").listview('refresh');
		} catch(e) {
		}
	}	


	
	
	$("body").on("pagebeforeshow", "#page-tag-videolist", this.init);
	$("#page-tag-videolist #listview-item-more").on("click", this.searchVideos);
	$("#page-tag-videolist").on("click", "#btn-refresh", onRefresh);
	$("#page-tag-videolist").on("click", ".btn-listview-sort", onSort);
});